package com.zbkj.service.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.common.exception.CrmebException;
import com.zbkj.common.model.custom.Custom;
import com.zbkj.common.model.custom.CustomAttach;
import com.zbkj.common.request.CustomAttachUploadRequest;
import com.zbkj.common.response.CustomShowFileResponse;
import com.zbkj.common.util.BeanUtils;
import com.zbkj.service.dao.CustomAttachDao;
import com.zbkj.service.dao.CustomDao;
import com.zbkj.service.service.CustomAttachService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service

public class CustomAttachServiceImpl extends ServiceImpl<CustomAttachDao, CustomAttach> implements CustomAttachService {

    @Resource
    CustomAttachDao dao;

    @Autowired
    CustomDao customDao;

    @Autowired
    private TransactionTemplate transactionTemplate;
    @Override
    public List<CustomShowFileResponse> showFile(Integer id,Integer type) {
        List<CustomAttach> list = dao.showFile(id,type);
        List<CustomShowFileResponse> responseList = list.stream().map(e->{
            if(e.getIsShow()&&!e.getIsDel()) {
                CustomShowFileResponse response = new CustomShowFileResponse();
                BeanUtils.copyProperties(e, response);
                return response;
            }
            return null;
        }).collect(Collectors.toList());
        responseList.removeAll(Collections.singleton(null));
        return responseList;
    }

    @Override
    public String uploadFile(CustomAttachUploadRequest request) {
        CustomAttach customAttach = new CustomAttach();
        BeanUtils.copyProperties(request,customAttach);
        Custom custom = customDao.selectById(request.getCustomId());

        switch (request.getType()){
            case 1:
                if(custom.getStatus()>=2)
                    throw new CrmebException("错误的上传，该定制已存在初稿");
                custom.setStatus(2);
                break;
            case 2:
                if(custom.getStatus()==4)
                    throw new CrmebException("错误的上传，该定制已上传终稿");
                custom.setStatus(4);
                break;
        }

        Boolean execute = transactionTemplate.execute(e->{
            save(customAttach);
            customDao.updateById(custom);
            return Boolean.TRUE;
        });

        if(!execute){
            throw new CrmebException("附件上传时遇到错误");
        }

        return "上传成功";
    }
}
